#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QMessageBox>
#include <QInputDialog>
#include <QKeyEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , server(new QTcpServer(this))
    , socket(nullptr)
    , clientConnection(nullptr)
    , isServerMode(false)  // 添加这个标志
{
    ui->setupUi(this);
    ui->chatDisplay->setReadOnly(true);
    ui->sendButton->setEnabled(false);

    connect(server, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection);
    connect(ui->messageInput, &QTextEdit::textChanged, [this]() {
        ui->sendButton->setEnabled(!ui->messageInput->toPlainText().isEmpty());
    });

    // 启动服务器
    if (server->listen(QHostAddress::Any, 12345)) {
        appendMessage(QString("服务器已在端口 %1 启动，等待连接...").arg(server->serverPort()));
        ui->statusLabel->setText(QString("等待连接 (端口: %1)").arg(server->serverPort()));
        isServerMode = true;
    } else {
        appendMessage("无法启动服务器: " + server->errorString());
        ui->statusLabel->setText("服务器启动失败");
    }

    // 支持回车发送
    ui->messageInput->installEventFilter(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_sendButton_clicked()
{
    QString message = ui->messageInput->toPlainText().trimmed();
    if (!message.isEmpty()) {
        sendMessage(message);
        ui->messageInput->clear();
    }
}

void MainWindow::on_connectButton_clicked()
{
    QString address = QInputDialog::getText(this, "连接到对方", "请输入对方IP地址:",
                                            QLineEdit::Normal, "127.0.0.1");
    if (!address.isEmpty()) {
        if (socket) {
            socket->deleteLater();
        }

        socket = new QTcpSocket(this);
        connect(socket, &QTcpSocket::connected, this, &MainWindow::handleConnected);
        connect(socket, &QTcpSocket::disconnected, this, &MainWindow::handleDisconnected);
        connect(socket, &QTcpSocket::readyRead, this, &MainWindow::handleReadyRead);
        connect(socket, &QAbstractSocket::errorOccurred, this, &MainWindow::handleError);

        socket->connectToHost(address, 12345);
    }
}

void MainWindow::handleNewConnection()
{
    clientConnection = server->nextPendingConnection();
    connect(clientConnection, &QTcpSocket::readyRead, this, &MainWindow::handleReadyRead);
    connect(clientConnection, &QTcpSocket::disconnected, this, &MainWindow::handleClientDisconnected);

    appendMessage("对方已连接");
    ui->statusLabel->setText("已连接 (作为服务器)");
    ui->sendButton->setEnabled(true);
    ui->connectButton->setEnabled(false);
    isServerMode = true;  // 标记为服务器模式
}

void MainWindow::handleClientDisconnected()
{
    appendMessage("对方已断开连接");
    ui->statusLabel->setText("连接已断开");
    ui->sendButton->setEnabled(false);
    ui->connectButton->setEnabled(true);

    if (clientConnection) {
        clientConnection->deleteLater();
        clientConnection = nullptr;
    }
    isServerMode = false;
}

void MainWindow::handleConnected()
{
    appendMessage(QString("已连接到 %1:%2").arg(socket->peerAddress().toString()).arg(socket->peerPort()));
    ui->statusLabel->setText(QString("已连接到 %1:%2").arg(socket->peerAddress().toString()).arg(socket->peerPort()));
    ui->sendButton->setEnabled(true);
    ui->connectButton->setEnabled(false);
    isServerMode = false;  // 标记为客户端模式
}

void MainWindow::handleDisconnected()
{
    appendMessage("连接已断开");
    ui->statusLabel->setText("连接已断开");
    ui->sendButton->setEnabled(false);
    ui->connectButton->setEnabled(true);

    if (socket) {
        socket->deleteLater();
        socket = nullptr;
    }
    isServerMode = false;
}

void MainWindow::handleError(QAbstractSocket::SocketError socketError)
{
    QString errorString;
    switch (socketError) {
    case QAbstractSocket::ConnectionRefusedError:
        errorString = "连接被拒绝";
        break;
    case QAbstractSocket::RemoteHostClosedError:
        errorString = "远程主机关闭连接";
        break;
    case QAbstractSocket::HostNotFoundError:
        errorString = "找不到主机";
        break;
    default:
        errorString = socket->errorString();
        break;
    }

    appendMessage("连接错误: " + errorString);
    ui->statusLabel->setText("连接错误");

    if (socket) {
        socket->deleteLater();
        socket = nullptr;
    }
    isServerMode = false;
}

void MainWindow::sendMessage(const QString &message)
{
    // 在本地显示自己发送的消息（立即显示，无需等待网络）
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString localMessage = QString("[%1] 我: %2").arg(timestamp).arg(message);
    appendMessage(localMessage);

    // 通过网络发送消息给对方
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_6_5);
    out << (quint16)0;
    out << message;
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    if (socket && socket->state() == QAbstractSocket::ConnectedState) {
        socket->write(block);
    } else if (clientConnection && clientConnection->state() == QAbstractSocket::ConnectedState) {
        clientConnection->write(block);
    } else {
        appendMessage("错误: 未连接到对方");
    }
}

void MainWindow::handleReadyRead()
{
    QTcpSocket *senderSocket = qobject_cast<QTcpSocket*>(sender());
    if (!senderSocket)
        return;

    QDataStream in(senderSocket);
    in.setVersion(QDataStream::Qt_6_5);

    while (senderSocket->bytesAvailable() >= sizeof(quint16)) {
        quint16 blockSize;
        in >> blockSize;

        if (senderSocket->bytesAvailable() < blockSize)
            return;

        QString message;
        in >> message;

        // 关键修改：只有当消息不是自己发送的时候才显示
        QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
        QString remoteMessage = QString("[%1] 对方: %2").arg(timestamp).arg(message);
        appendMessage(remoteMessage);
    }
}

void MainWindow::appendMessage(const QString &message)
{
    ui->chatDisplay->append(message);
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == ui->messageInput && event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if ((keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) &&
            keyEvent->modifiers() == Qt::NoModifier) {
            on_sendButton_clicked();
            return true;
        }
    }
    return QMainWindow::eventFilter(obj, event);
}
